<template>
  <div class="ticket-grab">
    <a-card title="抢票管理" :bordered="false">
      <template #extra>
        <a-button type="primary" @click="showAddModal">新增抢票任务</a-button>
      </template>

      <a-table :columns="columns" :data-source="ticketTasks" :loading="loading">
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'requiredCount'">
            <a @click="showPersonList(record, 'required')">查看名单 ({{ record.requiredList?.length || 0 }})</a>
          </template>
          <template v-if="column.key === 'currentCount'">
            <a @click="showPersonList(record, 'current')">查看名单 ({{ record.currentList?.length || 0 }})</a>
          </template>
          <template v-if="column.key === 'action'">
            <a-space>
              <router-link :to="{ name: 'PersonList', params: { taskId: record.key } }">
                <a-button type="primary">添加名单</a-button>
              </router-link>
              <a-divider type="vertical" />
              <a @click="editTask(record)">编辑</a>
              <a @click="viewSyp(record)">查看剩余票</a>
              <a-divider type="vertical" />
              <a-popconfirm title="确定要删除这个抢票任务吗？" @confirm="deleteTask(record)">
                <a class="danger">删除</a>
              </a-popconfirm>
            </a-space>
          </template>
        </template>
      </a-table>
    </a-card>

    <!-- 新增/编辑抢票任务对话框 -->
    <a-modal v-model:visible="taskModalVisible" :title="isEdit ? '编辑抢票任务' : '新增抢票任务'" @ok="handleTaskModalOk"
      @cancel="handleTaskModalCancel">
      <a-form :model="taskForm" :rules="taskRules" ref="taskFormRef">
        <a-form-item label="日期" name="date">
          <a-date-picker v-model:value="taskForm.date" style="width: 100%" />
        </a-form-item>
        <a-form-item label="门票类型" name="ticketType">
          <a-select v-model:value="taskForm.ticketType">
            <a-select-option value="故宫博物院">故宫博物院</a-select-option>
            <a-select-option value="国家博物馆">国家博物馆</a-select-option>
            <a-select-option value="颐和园">颐和园</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="需抢票人数" name="requiredCount">
          <a-input-number v-model:value="taskForm.requiredCount" :min="1" style="width: 100%" />
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 人员名单对话框 -->
    <a-modal v-model:visible="personListVisible" :title="personListType === 'required' ? '需抢票人员名单' : '已抢票人员名单'"
      width="800px" @cancel="handlePersonListCancel">
      <a-table :columns="personColumns" :data-source="currentPersonList" :loading="personListLoading">
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'paymentStatus'">
            <a-tag :color="record.paymentStatus ? 'green' : 'red'">
              {{ record.paymentStatus ? '已付款' : '未付款' }}
            </a-tag>
          </template>
        </template>
      </a-table>
    </a-modal>

    <!-- 添加人员名单对话框 -->
    <a-modal v-model:visible="addPersonModalVisible" title="添加人员名单" @ok="handleAddPersonModalOk"
      @cancel="handleAddPersonModalCancel">
      <a-form :model="personForm" :rules="personRules" ref="personFormRef">
        <a-form-item label="姓名" name="name">
          <a-input v-model:value="personForm.name" />
        </a-form-item>
        <a-form-item label="身份证号码" name="idNumber">
          <a-input v-model:value="personForm.idNumber" />
        </a-form-item>
        <a-form-item label="手机号码" name="phone">
          <a-input v-model:value="personForm.phone" />
        </a-form-item>
        <a-form-item label="付款状态" name="paymentStatus">
          <a-switch v-model:checked="personForm.paymentStatus" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, reactive, getCurrentInstance } from 'vue'
import { message } from 'ant-design-vue'
import dayjs from 'dayjs'
const { proxy } = getCurrentInstance()

// 表格列定义
const columns = [
  {
    title: '日期',
    dataIndex: 'date',
    key: 'date',
  },
  {
    title: '门票类型',
    dataIndex: 'ticketType',
    key: 'ticketType',
  },
  {
    title: '需抢票人数',
    dataIndex: 'requiredCount',
    key: 'requiredCount',
  },
  {
    title: '已抢票人数',
    dataIndex: 'currentCount',
    key: 'currentCount',
  },
  {
    title: '操作',
    key: 'action',
  },
]

// 人员名单表格列定义
const personColumns = [
  {
    title: '姓名',
    dataIndex: 'name',
    key: 'name',
  },
  {
    title: '身份证号码',
    dataIndex: 'idNumber',
    key: 'idNumber',
  },
  {
    title: '手机号码',
    dataIndex: 'phone',
    key: 'phone',
  },
  {
    title: '付款状态',
    dataIndex: 'paymentStatus',
    key: 'paymentStatus',
  },
]

// 抢票任务数据
const ticketTasks = ref([
  {
    key: '1',
    date: '2024-03-20',
    ticketType: '故宫博物院',
    requiredCount: 10,
    currentCount: 5,
    requiredList: [
      {
        key: '1',
        name: '张三',
        idNumber: '110101199001011234',
        phone: '13800138000',
        paymentStatus: true,
      },
      {
        key: '2',
        name: '李四',
        idNumber: '110101199001011235',
        phone: '13800138001',
        paymentStatus: false,
      },
    ],
    currentList: [
      {
        key: '1',
        name: '张三',
        idNumber: '110101199001011234',
        phone: '13800138000',
        paymentStatus: true,
      },
    ],
  },
])

// 加载状态
const loading = ref(false)
const personListLoading = ref(false)

// 模态框状态
const taskModalVisible = ref(false)
const personListVisible = ref(false)
const isEdit = ref(false)

// 表单引用
const taskFormRef = ref(null)

// 当前查看的人员名单
const currentPersonList = ref([])

// 表单数据
const taskForm = reactive({
  date: null,
  ticketType: undefined,
  requiredCount: 1,
})

// 表单验证规则
const taskRules = {
  date: [{ required: true, message: '请选择日期' }],
  ticketType: [{ required: true, message: '请选择门票类型' }],
  requiredCount: [{ required: true, message: '请输入需抢票人数' }],
}

// 人员名单类型
const personListType = ref('required')

// 添加人员名单模态框状态
const addPersonModalVisible = ref(false)
const personFormRef = ref(null)
const currentTask = ref(null)

// 人员表单数据
const personForm = reactive({
  name: '',
  idNumber: '',
  phone: '',
  paymentStatus: false,
})

// 人员表单验证规则
const personRules = {
  name: [{ required: true, message: '请输入姓名' }],
  idNumber: [{ required: true, message: '请输入身份证号码' }],
  phone: [{ required: true, message: '请输入手机号码' }],
}

// 显示新增对话框
const showAddModal = () => {
  isEdit.value = false
  taskForm.date = null
  taskForm.ticketType = undefined
  taskForm.requiredCount = 1
  taskModalVisible.value = true
}

// 编辑抢票任务
const editTask = (record) => {
  // 发起请求
  proxy.$http({
    method: 'get',
    url: `/springai/qp/qmpp`
  })
    .then(response => {
      debugger
      console.log('响应数据:', response.data);
      // 处理返回的JSON数据
      if (response.data.code === 200) {
        const dateManages = response.data.dateManages;
        console.log('可用票数:', dateManages.availableTicket);
        console.log('预约状态:', dateManages.text);
      }
    })
    .catch(error => {
      console.error('请求失败:', error);
    });
}


// 编辑抢票任务
const viewSyp = (record) => {
  isEdit.value = true
  Object.assign(taskForm, {
    ...record,
    date: dayjs(record.date),
  })
  taskModalVisible.value = true
}



// 删除抢票任务
const deleteTask = (record) => {
  const index = ticketTasks.value.findIndex(item => item.key === record.key)
  if (index > -1) {
    ticketTasks.value.splice(index, 1)
    message.success('删除成功')
  }
}

// 显示人员名单
const showPersonList = (record, type) => {
  personListType.value = type
  currentPersonList.value = type === 'required' ? record.requiredList || [] : record.currentList || []
  personListVisible.value = true
}

// 显示添加人员名单对话框
const showAddPersonModal = (record) => {
  currentTask.value = record
  personForm.name = ''
  personForm.idNumber = ''
  personForm.phone = ''
  personForm.paymentStatus = false
  addPersonModalVisible.value = true
}

// 处理抢票任务模态框确认
const handleTaskModalOk = () => {
  taskFormRef.value.validate().then(() => {
    const taskData = {
      ...taskForm,
      date: taskForm.date.format('YYYY-MM-DD'),
      currentCount: 0,
      requiredList: [],
      currentList: [],
    }

    if (isEdit.value) {
      const index = ticketTasks.value.findIndex(item => item.key === taskForm.key)
      if (index > -1) {
        ticketTasks.value[index] = { ...ticketTasks.value[index], ...taskData }
      }
    } else {
      ticketTasks.value.push({
        key: Date.now().toString(),
        ...taskData,
      })
    }
    taskModalVisible.value = false
    message.success('保存成功')
  })
}

// 处理抢票任务模态框取消
const handleTaskModalCancel = () => {
  taskModalVisible.value = false
}

// 处理人员名单对话框取消
const handlePersonListCancel = () => {
  personListVisible.value = false
}

// 处理添加人员名单确认
const handleAddPersonModalOk = () => {
  personFormRef.value.validate().then(() => {
    const personData = {
      key: Date.now().toString(),
      ...personForm,
    }

    if (!currentTask.value.requiredList) {
      currentTask.value.requiredList = []
    }
    currentTask.value.requiredList.push(personData)

    addPersonModalVisible.value = false
    message.success('添加成功')
  })
}

// 处理添加人员名单取消
const handleAddPersonModalCancel = () => {
  addPersonModalVisible.value = false
}
</script>

<style scoped>
.ticket-grab {
  padding: 24px;
}

.danger {
  color: #ff4d4f;
}
</style>